import axios from '../utils/axios'

export const login = async ({ password, email }) => {
  let user = await axios.get(`/users?_embed=emails&password=${password}`)
  if (user.length) {
    let userEmail = await axios.get(`/emails?email=${email}`)
    if (userEmail.length) {
      user = user.find(user => {
        return userEmail.some(item => {
          return user.id === item.userId
        })
      })
      return axios.get(`/users?_embed=emails&id=${user.id}`)
    }
  }
  return Promise.resolve([])
}

//账号注册
export const register = async ({ username, password, sex, birthDate, phoneNumber, email, img }) => {
  let res = await axios.post(`/users`, {
    username,
    password,
    sex,
    birthDate,
    phoneNumber,
    img
  })
  await axios.post(`/emails`, { email, userId: res.id })
  return axios.get(`/users/${res.id}?_embed=emails`)
}
//查找邮箱是否被注册
export const isHaveEmail = email => axios.get('/emails', { params: { email } })
//根据userId重置密码
export const resetpassw = ({ id, password }) =>
  axios.patch(`/users/${id}`, {
    password
  })
//修改用户信息
export const modifyInfo = async ({ username, sex, birthDate, phoneNumber, id, emails, img }) => {
  await axios.patch(`/users/${id}`, {
    username,
    sex,
    birthDate,
    phoneNumber,
    img
  })
  await axios.patch(`/emails/${emails[0].id}`, {
    email: emails[0].email
  })
  return axios.get(`/users/${id}?_embed=emails`)
}
